import {
	cloudmateURL,
	PWD_ENC_PRE,
	OAUTH2_PASSWORD_CLIENT

} from '@/utils/requestURL.js'
import crypto from "crypto-js";
import Base64 from 'base-64'
import {
	weBtoa
} from '@/utils/btoa.js'
import {
	encryption
} from '@/utils/index.js'
let requestNum = 0;
let numTimer = null;

let flg = false;
let timerReferesh = null;
const $request = (url, data, method = 'POST', headers = "application/json", type = 'request') => {
	return new Promise(async (resolve, reject) => {

		await judgetoken()

		if (flg) {

			clearInterval(timerReferesh)
			timerReferesh = setInterval(() => {
				console.log(flg);
				if (!flg) {
					clearInterval(timerReferesh)
					requestHandle(url, data, method, headers, resolve, type,reject)
				}
			}, 500)
		} else {
			await requestHandle(url, data, method, headers, resolve, type,reject)
		}

	})
}

const requestHandle = async (url, data, method, headers, resolve, type,reject) => {

	let accessTokenText = uni.getStorageSync('accessToken')
	let requestHeader = {
		'Content-Type': headers,
	}

	if (accessTokenText) {
		requestHeader.AUTHORIZATION = 'Bearer ' + accessTokenText
	}
	if (url == '/reg/loginPwd') {
		requestHeader.AUTHORIZATION = 'Basic ' + weBtoa(OAUTH2_PASSWORD_CLIENT)
	}
	const penc = encryption(PWD_ENC_PRE + (new Date().getTime()).toString())
	requestHeader.QLO = penc

	let options = {
		url: url,
		data: data,
		method: method,
		header: url,
	}
	// 监听网络网络变化
	uni.getNetworkType({
		success: async res => {
			if (res.networkType == 'none') {
				// uni.showToast({
				// 	title:'No Network'+url,
				// 	icon:'none',
				// 	duration:2000
				// })
				return false
			}
		},
	
	})
	
	if (type == 'upload') {
		uni.uploadFile({
			url: cloudmateURL + url,
			filePath: data,
			method: method,
			name: 'file',
			header: requestHeader,
			success: (res) => {
				console.log(res);
				resolve(res.data)
			},
			fail(error) {
				reject(error);
			},
			complete(res) {
				console.log(res.statusCode);
				let status = res.statusCode


				switch (status) {

					case 401:
					case 424:
						uni.clearStorageSync()
						uni.setStorageSync('overdueLogin', true)
						uni.reLaunch({
							url: `../../pages/login/login`
						})
						break;
					case 404:
						uni.showToast({
							title: '请求地址有误!',
							duration: 2000,
							icon: 'error'
						});
						break;
					case 500:
					case 503:
						uni.showToast({
							title: '服务器出错!',
							duration: 2000,
							icon: 'error'
						});
						break;
				}
			}
		})
	} else {
		uni.request({
			url: cloudmateURL + url,
			method: method,
			data: data,
			header: requestHeader,
			success(res) {
				// 返回成功的信息
				resolve(res.data)
			},
			fail(error) {
				console.log(error,url);
				reject(error);
			},
			complete(res) {
				let status = res.statusCode


				switch (status) {
					case 401:
					case 424:
						uni.clearStorageSync()
						uni.setStorageSync('overdueLogin', true)
						uni.reLaunch({
							url: `../../pages/login/login`
						})
						break;
					case 404:
						uni.showToast({
							title: '请求地址有误!',
							duration: 2000,
							icon: 'error'
						});
						break;
					case 500:
						uni.showToast({
							title: '服务器出错!',
							duration: 2000,
							icon: 'error'
						});
						break;

				}
			}
		})
	}
}
// 登录时间 + 多久的过期时间 < 当前时间
var judgetoken = async function() {
	flg = false;
	if (uni.getStorageSync('loginInfo')) {
		let accessTokenText = uni.getStorageSync('accessToken');
		// let expirationtime = uni.getStorageSync('expires_in'); //减少半个小时天
		// let expirationtime = 0; //减少半个小时天
		let expirationtime = 60 * 60 * 24 * 2; //登录之后两天后获取
		let logintimestamp = uni.getStorageSync('logintimestamp'); //登陆时间
		let currenttimestamp = Math.round(new Date() / 1000); //当前时间
		if (!accessTokenText || !logintimestamp) return
		if (logintimestamp + expirationtime <= currenttimestamp) {
			flg = true;
		}
		if (flg && requestNum == 0) {
			requestToken()
			return
		}
	}


}

var requestToken = async function() {
	requestNum = 1
	let accessTokenText = uni.getStorageSync('accessToken')

	let head = {
		'content-type': 'application/json',
		'AUTHORIZATION': 'Bearer ' + accessTokenText,
		"QLO": encryption(PWD_ENC_PRE + (new Date().getTime()).toString())
	}
	await uni.request({
		url: cloudmateURL + '/app/reg/refreshToken',
		method: 'POST',
		data: {
			'refresh_token': uni.getStorageSync('refreshToken'),
		},
		header: head,
		success(res) {
			console.log(res, flg);
			let resdata = res.data
			if (resdata.code == 0 && resdata.data.access_token) {
				uni.setStorageSync('accessToken', resdata.data.access_token)
				uni.setStorageSync('refreshToken', resdata.data.refresh_token)
				uni.setStorageSync('expires_in', res.data.expires_in)
				uni.setStorageSync('logintimestamp', Math.round(new Date() / 1000))

				flg = false

			} else {
				clearInterval(timerReferesh)
				uni.clearStorageSync()
				uni.setStorageSync('overdueLogin', true)

				uni.reLaunch({
					url: `../../pages/login/login`
				})
			}
		},
		complete(res) {
			let status = res.statusCode
			switch (status) {
				case 401:
				case 424:
					uni.clearStorageSync()
					uni.setStorageSync('overdueLogin', true)
					uni.reLaunch({
						url: `../../pages/login/login`
					})
					break;
				case 404:
					uni.showToast({
						title: '请求地址有误!',
						duration: 2000,
						icon: 'error'
					});
					break;
				case 500:
					uni.showToast({
						title: '服务器出错!',
						duration: 2000,
						icon: 'error'
					});
					break;

			}
		}
	})
	numTimer = setTimeout(() => {
		requestNum = 0;
		clearTimeout(numTimer)
	}, 5000);
}


const $get = (url, data, headers) => {
	return $request(url, data, 'GET', headers)
}
const $post = (url, data, headers) => {
	return $request(url, data, 'POST', headers)
}
const $uploadFile = (url, data, headers) => {
	return $request(url, data, 'POST', headers, 'upload')
}
const $delete = (url, data) => {
	return $request(url, data, 'DELETE')
}
uni.$request = $request
uni.$get = $get
uni.$post = $post
uni.$delete = $delete
uni.$uploadFile = $uploadFile